function [s m in mins hdsm]=RAICAR1D_fin(dire,n1,n2,n3)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%R.Magalhaes, Paris, July 2019
%Function to calculate the logarithm of the histogram distribution of the
%correlations for the different permutation numbers (hdsm) as well as it's minimum
%points (m) and matching index within the histogram(in) and real value (mins),
%an array with the number of permutations above the reproducibility
%threshold, most reproducible component of each iteration and total
%reproducibility score (s)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Must choose the range of values to build correlation matrix
%and step size (e.g between 5 and 400 permutations in steps of 5
%Usage: RAICARD1D_fin('directory',min number of permutations, size step,max number of permutations);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Loaded file can be created with matlab function RAICAR1D made available
%within the same set of functions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%This software is provided under a Free for Non-Commercial Use Only Agreement and a Non-Commercial use agreement
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%contact: ricardo.magalhaes@cea.fr

load(strcat(dire,'/CRCM_mat1D400'),'set','sizes','index','crcm');
setall=set;sizesall=sizes;indexall=index;crcmall=crcm;
clear set, sizes, index, crcm;
k=1;
for n=n1:n2:n3
set=setall(1:n,1:n);
sizes=sizesall(1:n);
index=indexall(:,1:n);
crcm=crcmall(1:sum(sizes),1:sum(sizes));

load(strcat(dire,'/RAICAR1Dresultsnew',int2str(n)),'comp');

d=[];
for i=1:n
for j=1:size(set(1,i).mat,1)
d=[d set(1,i).mat(j,:)];
end
end
hd=hist(abs(d),200);
hdlog=log(hd);
hdsm=smooth(hdlog,75,'sgolay');
[m(k),in(k)]=min(hdsm);

for i=1:63
s(k,i,1)=length(find(squeeze(comp(1,i).r(:,3))>=(in(k)/200)));
s(k,i,2)=comp(1,i).r(1,1);
s(k,i,3)=sum(squeeze(comp(1,i).r(:,3)));
end
mins(k)=(in(k)/200);
k=k+1;
end

end